<?php
namespace api\components;

use yii\web\JsonResponseFormatter;
use yii\helpers\Json;

class ApiJsonResponse extends JsonResponseFormatter
{
    public $encodeOptions = 32;
    /**
     * Formats response data in JSON format.
     * @param Response $response
     */
    protected function formatJson($response)
    {
        if ($response->data !== null) {
            $options = $this->encodeOptions;
            if ($this->prettyPrint) {
                $options |= JSON_PRETTY_PRINT;
            }
            $res = [];
            if($response->getStatusCode() == 200){
                $res['code'] = 200;
                $res['data'] = $response->data;
                $res['message'] = '';
            }else{
                $res['code'] = $response->getStatusCode();
                $res['message'] = $response->data['message'] ?? '';
                $res['data'] = [];
            }
            $response->content = Json::encode($res, $options);
        } elseif ($response->content === null) {
            $response->content = 'null';
        }
    }
}